package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    /**
     * 完善个人信息-基本信息
     *
     * @param param
     * @param token
     * @return
     */
    public boolean saveUserInfo(Map<String, String> param, String token) {

        //验证token
        User user = this.userService.queryUserByToken(token);
        if (null == user){
            //token失效
            return false;
        }

        //token还未失效,将数据保存到userInfo中
        UserInfo userInfo = new UserInfo();

        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equals(param.get("gender"),"man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        //将userInfo保存到数据库,并返回结果
        return this.userInfoMapper.insert(userInfo) == 1;
    }

    /**
     * 完善个人信息-头像上传
     *
     * @param file
     * @param token
     * @return
     */
    public boolean saveUserLogo(MultipartFile file, String token) {

        //校验token
        User user = this.userService.queryUserByToken(token);
        if (null == user){
            return false;
        }

        try {
            //人脸识别,如果不是返回false
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!b){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //上传头像到阿里云OOS中
        PicUploadResult result = this.picUploadService.upload(file);
        //校验头像是否上传成功
        if (StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }
        //将头衔保存到userInfo中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        //条件对象
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());

        return this.userInfoMapper.update(userInfo,queryWrapper) == 1;
    }
}
